<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .myradio{display: flex;}
        .myradio span{display: block;border-radius: 50%;width:16px;height:16px;border:solid 4px #ccc;margin: 0 4px;cursor: pointer;}
        .myradio span.active{background: #222;}
    </style>
</head>
<body>
    <input type="radio" name="sex" id="a">
    <input type="radio" name="sex" >

    <div class="myradio">
        <span></span>
        <span></span>
        <span></span>
        <span class="a"></span>
        <span></span>
        <span></span>
    </div>
</body>
<script>

    const myradio = document.querySelector(".myradio");
    const myradios = document.querySelectorAll(".myradio span");

    // 设置默认值，根据默认值设置默认效果
    let index = 0;
    myradios[index].className = "active";
    myradios[index].checked = true;

    // 遍历所有元素，添加索引，设置默认checked
    [...myradios].forEach((val,idx)=>{
        val.index = idx;
        val.checked = false;
    })

    // 可选：鼠标进入，显示浅色预选中效果，点击之后再显示被选中效果
    myradio.addEventListener("mouseover", function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        // 事件目标为span，且属于未选中状态时，才有浅色预选中效果
        if(target.tagName === "SPAN" && target.className === ""){
            target.style.background = "#aaa";
        }
    })
    // 鼠标离开，清除预选中效果
    myradio.onmouseout = function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.tagName === "SPAN"){
            target.style.background = "";
        }
    }
    
    // 核心功能：点击选中
    myradio.addEventListener("click", function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.tagName === "SPAN"){
            // 清除上一个选中效果
            myradios[index].className = "";
            myradios[index].checked = false;
            // 当前元素添加选中效果
            target.className = "active";
            target.checked = true;
            // 将当前索引设置成下次要清除的索引
            index = target.index;
            // 主动执行鼠标离开事件：取消预选中效果
            myradio.onmouseout();
        }
    })




</script>
</html>